<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/30
 * Time: 15:05
 */

namespace app\alliance\controller;


use app\service\MemberService;
use app\service\TaskService;
use Redis\Redis;
use think\Db;

class Player extends Common
{
    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 创业联盟
     */
    function alliance()
    {
        $redis = new Redis();
        # 查询用户下一个等级信息
        $nextLevel = $this->memberInfo['level'] + 1;
        if ($nextLevel > 12) {
            $nextLevelInfo = array();
            $nextLevelMsg = "已经是最高等级";
        } else {
            $nextLevelInfo = $redis->hGetJson('memberLevelInfo', strval($nextLevel));
            $nextLevelMsg = $nextLevelInfo['title'];
        }
        # 升级条件总数
        $upgradeTotal = 0;
        # 完成升级条件总数
        $completeTotal = 0;
        # 升级标准(需要有多少个等级玩家)
        $gradeNumberLimit = array();
        # 升级条件提示
        $_tip = "";
        if ($nextLevelInfo['is_limits'] == 2) {
            # 已激活的 真实用户
            $gradeNumberLimit = Db::table('industry_level_limits ill')
                ->field('member_num,member_level,title,
                if((select count(id) from member where member.status=5 and member.fictitious=0 and level=ill.member_level and team_id = ' . $this->memberInfo['team_id'] . ')>member_num,
                member_num,(select count(id) from member where level=ill.member_level and team_id = ' . $this->memberInfo['team_id'] . ')) completed_num')
                ->leftJoin('member_level ml', 'ml.level=ill.member_level')
                ->where(array('ill.level_id' => $nextLevelInfo['id']))
                ->order("member_level asc")
                ->select();
            $upgradeTotal += array_sum(array_column($gradeNumberLimit, 'member_num'));
            $completeTotal += array_sum(array_column($gradeNumberLimit, 'completed_num'));
        }
        # 判断升级条件(完成情况)(交易次数 , 直推人数 , 团队人数 , 消费金额限制)
        $upgradeStandard = array('trade_num_complete' => 0, 'share_num_complete' => 0, 'team_people_complete' => 0, 'consumption_amount_complete' => 0);
        if ($nextLevelInfo['trade_num'] > 0) {
            # 查询交易次数
            $upgradeStandard['trade_num_complete'] = Db::table('log_trad')->where("seller_code = '" . $this->code . "' or buyer_code = '" . $this->code . "'")->count();
            $upgradeTotal += $nextLevelInfo['trade_num'];
            if ($upgradeStandard['trade_num_complete'] > $nextLevelInfo['trade_num']) {
                $upgradeStandard['trade_num_complete'] = $nextLevelInfo['trade_num'];
            }
            $completeTotal += $upgradeStandard['trade_num_complete'];
            if ($nextLevel == 2) {
                if ($upgradeStandard['trade_num_complete'] < $nextLevelInfo['trade_num']) {
                    $_tip .= ",交易" . ($nextLevelInfo['trade_num'] - $upgradeStandard['trade_num_complete']) . '次';
                } else {
                    $_tip .= ",交易0次";
                }
            }
        }
        if ($nextLevelInfo['share_num'] > 0) {
            # 查询直推人数(已激活的 真实用户)
            $upgradeStandard['share_num_complete'] = Db::table('member')->where(array('p_code' => $this->code,'status'=>5,'fictitious'=>0))->count();
            $upgradeTotal += $nextLevelInfo['share_num'];
            if ($upgradeStandard['share_num_complete'] > $nextLevelInfo['share_num']) {
                $upgradeStandard['share_num_complete'] = $nextLevelInfo['share_num'];
            }
            $completeTotal += $upgradeStandard['share_num_complete'];
            if ($upgradeStandard['share_num_complete'] < $nextLevelInfo['share_num']) {
                $_tip .= ",推荐玩家" . ($nextLevelInfo['share_num'] - $upgradeStandard['share_num_complete']) . '人';
            } else {
                $_tip .= ",推荐玩家0人";
            }
        }
        if ($nextLevelInfo['team_people'] > 0) {
            # 查询团队人数(已激活的真实用户)
            $upgradeStandard['team_people_complete'] = Db::table('member')->field('code')
                ->where("code != '" . $this->code . "'")
                ->where("
            (code in (select code from member where status=5 and fictitious=0 and p_code in(select code from member where p_code = '" . $this->code . "')))")
//                ->where("(code in ((select code from member where p_code in
//            (select code from member where p_code in(select code from member where p_code = '" . $this->code . "'))),
//            (select code from member where p_code in(select code from member where p_code = '" . $this->code . "')),
//            (select code from member where p_code = '" . $this->code . "')))")
                ->count();
            $upgradeTotal += $nextLevelInfo['team_people'];
            if ($upgradeStandard['team_people_complete'] > $nextLevelInfo['team_people']) {
                $upgradeStandard['team_people_complete'] = $nextLevelInfo['team_people'];
            }
            $completeTotal += $upgradeStandard['team_people_complete'];
            if ($upgradeStandard['team_people_complete'] < $nextLevelInfo['team_people']) {
                $_tip .= ",关联玩家" . ($nextLevelInfo['team_people'] - $upgradeStandard['team_people_complete']) . '人';
            } else {
                $_tip .= ",关联玩家0人";
            }
        }
        if ($nextLevelInfo['consumption_amount'] > 0) {
            # 消费金额限制
            $upgradeStandard['consumption_amount_complete'] = Db::table('log_integral')->where(array('member_code' => $this->code, 'type_branch' => 7))->sum('total_money');
//            $upgradeTotal += $nextLevelInfo['consumption_amount'];
//            if ($upgradeStandard['consumption_amount_complete'] < $nextLevelInfo['consumption_amount']) {
//                $completeTotal += $upgradeStandard['consumption_amount_complete'];
//            }
//            if ($upgradeStandard['consumption_amount_complete'] < $nextLevelInfo['consumption_amount']) {
//                $_tip .= ",消费" . ($nextLevelInfo['consumption_amount'] - $nextLevelInfo['consumption_amount_complete']) . '元';
//            }
        }
        # 激活账号的时间
        if (empty($this->memberInfo['activation_time'])) {
            $activation_time = 0;
        } else {
            $activation_time = ((strtotime(date('Y-m-d')) - strtotime(date('Y-m-d', strtotime($this->memberInfo['activation_time'])))) / 3600 / 24) + 1;
            if (empty($activation_time)) {
                $activation_time = 1;
            }
        }
        # 推荐的已激活玩家
        $activated = Db::table('member')->where("code != '" . $this->code . "'")->where(array('p_code' => $this->code))->where(array('status' => 5))->count('id');
        # 推荐的未激活的玩家
        $notActive = Db::table('member')->where("code != '" . $this->code . "'")->where(array('p_code' => $this->code))->where("status != 5")->count('id');
        # 累计推荐的玩家
        $recommend = $activated + $notActive;
        # 关联的玩家
        $teamNum = Db::table('member')->where("code != '" . $this->code . "'")
            ->where("
            (code in (select code from member where status=5 and fictitious=0 and p_code in(select code from member where p_code = '" . $this->code . "')))")
            ->count();
//dump(Db::table('member')->getLastSql());
        # 不活跃玩家
        $inactive = Db::table('member m')
            ->where("(code in (select code from member where p_code in (select code from member where p_code in(select code from member where p_code = '" . $this->code . "'))))")
            ->where("m.code != '" . $this->code . "'")
            ->where("(select count(id) from member_business_grid where member_code=m.code and status = 1 and member_business_id=0 and start_time < '" . date('Y-m-d H:i:s', strtotime('-24 hours')) . "' ) > 0")
            ->count();

        if ($completeTotal > $upgradeTotal) {
            $completeTotal = $upgradeTotal;
        }
        if ($upgradeTotal == 0) {
            $completeTotal = 1;
            $upgradeTotal = 1;
        }
        return array('status' => true, 'msg' => '查询成功',
            'currentLevel' => $this->memberInfo['title'],// 当前等级名称
            'nextLevel' => $nextLevelInfo, // 下一等级信息
            'nextLevelMsg' => $nextLevelMsg,//下一等级提示信息
            'gradeNumberLimit' => $gradeNumberLimit,//升级标准(需要有多少个等级玩家)
            'upgradeStandard' => $upgradeStandard,//判断升级条件(完成情况)(交易次数 , 直推人数 , 团队人数 , 消费金额限制)
            'activation_time' => $activation_time,//账号激活天数
            'income' => priceFormat($this->memberInfo['income']),//累计收益
            'activated' => $activated,//推荐的已激活玩家
            'notActive' => $notActive,//推荐的未激活的玩家
            'recommend' => $recommend,//累计推荐的玩家
            'team_num' => $teamNum,//关联的玩家
            'inactive' => $inactive,//不活跃玩家
            'active' => $teamNum - $inactive,//活跃玩家
            'upgradeTotal' => $upgradeTotal,//升级条件总数
            'completeTotal' => $completeTotal,//完成升级条件总数
            'tip' => trim($_tip, ','),//升级提示信息
        );
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询相关玩家信息
     */
    function associatedPlayers()
    {
        # 接收查询条件
        $mark = input('post.mark');
        # 搜索条件
        $searchInfo = input('post.searchInfo');
        if (!empty($mark)) {
            $listRows = 20;
            $pageMark = input('post.page');
            if (empty($pageMark)) {
                $pageMark = 0;
            }
            $page = $pageMark * $listRows;
            $markWhere = "";
            $searchWhere = "";
            if (!empty($searchInfo)) {
                $searchWhere = "m.phone like '%" . $searchInfo . "%' or m.code like '%" . $searchInfo . "%'";
            }
            if ($mark == 'activated') {
                # 已激活玩家
                $markWhere = array('p_code' => $this->code, 'status' => 5);
            } elseif ($mark == 'notActive') {
                # 未激活玩家
                $markWhere = "p_code = '" . $this->code . "' and status != 5";
            } elseif ($mark == 'related') {
                # 关联总玩家
//                $markWhere = "team_id = " . $this->memberInfo['team_id'] . " and code != '" . $this->code . "'";
//                $markWhere = "(code in ((select code from member where p_code in
//            (select code from member where p_code in(select code from member where p_code = '" . $this->code . "'))),
//            (select code from member where p_code in(select code from member where p_code = '" . $this->code . "'))))";
                $markWhere="
            (code in (select code from member where status=5 and fictitious=0 and p_code in(select code from member where p_code = '" . $this->code . "'))) ";
            } elseif ($mark == 'active') {
                # 活跃玩家   and (select count(id) from member_business_grid where m.code =member_code and status = 0) = 0
                $markWhere = "((code in ((select code from member 
                where p_code in(select code from member where p_code = '" . $this->code . "'))))) and 
                ((select count(mbg.id) from member_business_grid mbg,member_business mb where m.code=mbg.member_code and mbg.status = 1 and mbg.member_business_id!=0 
                and mbg.member_business_id=mb.id
                and mb.opera_start_time >= '" . date('Y-m-d H:i:s', strtotime('- 24 hours')) . "') > 0) ";
            } elseif ($mark == 'inactive') {
                # 不活跃玩家  (select count(id) from member_business_grid where member_code=m.code and status=0) > 0 or
                $markWhere = "((code in ((select code from member where p_code in(select code from member where p_code = '" . $this->code . "'))))) and 
                ((select count(id) from member_business_grid where member_code=m.code and status = 1 and member_business_id=0 
                and start_time < '" . date('Y-m-d H:i:s', strtotime('- 24 hours')) . "' ) > 0) "; //and m.level >= 3
            }
            # 查询相关的玩家信息
            $list = Db::table('member m')
                ->field('code,name,head_portrait,phone,(select count(id) from member where p_code= m.code) team_num,income,m.register_time,m.activation_time,province,city,area,address')
                ->leftJoin('member_property mp', 'mp.member_code=m.code')
                ->leftJoin('team t', 't.id=m.team_id')
                ->where($markWhere)
                ->where($searchWhere)
                ->limit($page, $listRows)
                ->select();
            //var_dump(Db::table("member")->getLastSql());
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    $list[$k]['head_portrait'] = imgUrl($v['head_portrait']);
                    $list[$k]['register_time'] = date('Y/m/d H:i', strtotime($v['register_time']));
                    $list[$k]['activation_time'] = date('Y/m/d H:i', strtotime($v['activation_time']));
                }
            }
            return array('status' => true, 'msg' => '查询成功', 'list' => $list, 'count' => count($list));
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 玩家任务列表
     */
    function taskList()
    {
        $task = new TaskService($this->code, $this->memberInfo['level']);
        $info = $task->taskList();
        return $info;
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询任务奖励
     */
    function taskPrize()
    {
        $taskId = input('post.taskId');
        if (!empty($taskId)) {
            # 查询任务奖励
            $info = Db::table('active_reward')
                ->where(array('active_id' => $taskId, 'active_category' => 2))
                ->order('id desc')
                ->select();
            return array('status' => true, 'msg' => '查询成功', 'info' => $info);
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 领取任务奖励
     */
    function receiveTaskReward()
    {
        $taskId = input('post.taskId');
        $member_taskId = input('post.member_taskId');
        if (!empty($taskId)) {
            # 修改玩家任务列表状态
            Db::table('member_task')->where(array('id' => $member_taskId))->update(array('finish_status' => 3, 'receive_time' => date("Y-m-d H:i:s")));
            # 领取任务奖励
            $res = MemberService::giveReward($this->memberInfo, $taskId, 2, true, false, false);
            $task = new TaskService($this->code, $this->memberInfo['level']);
            $task->taskAdd();
            return $res;
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 根据手机号/玩家ID/姓名  查询玩家列表
     */
    function getPlayerInfo()
    {
        $searchInfo = input('post.searchInfo');
        $mark = input('post.mark');
        $where = "";
        if ($mark == 'addFriends') {
            $where = "(select count(id) from friends where member_code = '".$this->code."' and friends_code=m.code and status = 2) =0";
        }
        if (!empty($searchInfo)) {
            # 手机号/玩家ID/姓名
            $info = Db::table('member m')
                ->field('m.name,m.head_portrait,m.address,m.code,income,team_num')
                ->leftJoin('member_property mp', 'mp.member_code=code')
                ->leftJoin('team t', 't.id=team_id')
//                ->where(array('team_id' => $this->memberInfo['team_id']))
                ->where("code != '" . strtoupper($this->code) . "'")
                ->where("name like '%" . $searchInfo . "%' or phone like '%" . $searchInfo . "%' or code like '%" . strtoupper($searchInfo) . "%'")
                ->where($where)
                ->select();
            if (!empty($info)) {
                foreach ($info as $k => $v) {
                    $info[$k]['head_portrait'] = imgUrl($v['head_portrait']);
                    $info[$k]['income'] = priceFormat($v['income']);
                }
                return array('status' => true, 'info' => $info);
            } else {
                return array('status' => false, 'msg' => '查询结果为空');
            }
        } else {
            return array('status' => false, 'msg' => '查询条件为空');
        }
    }
}